package com.ly.oa.service.info.impl;

import com.ly.core.Constants;
import com.ly.core.service.impl.BaseServiceImpl;
import com.ly.core.web.paging.PagingBean;
import com.ly.oa.dao.info.InMessageDao;
import com.ly.oa.dao.info.ShortMessageDao;
import com.ly.oa.dao.system.AppUserDao;
import com.ly.oa.model.info.InMessage;
import com.ly.oa.model.info.ShortMessage;
import com.ly.oa.model.system.AppUser;
import com.ly.oa.service.info.ShortMessageService;
import java.util.Date;
import java.util.List;
import javax.annotation.Resource;

public class ShortMessageServiceImpl extends BaseServiceImpl<ShortMessage> implements
		ShortMessageService {
	private ShortMessageDao messageDao;
	@Resource
	  private InMessageDao inMessageDao;
	@Resource
	  private AppUserDao appUserDao;
	
	public ShortMessageServiceImpl(ShortMessageDao dao) {
		super(dao);
		this.messageDao=dao;
	}

	@Override
	public List<ShortMessage> findAll(Long userId, PagingBean pb) {
		return messageDao.findAll(userId, pb);
	}

	@Override
	public List<ShortMessage> findByUser(Long userId) {
		return messageDao.findByUser(userId);
	}

	@Override
	public List searchShortMessage(Long userId,
			ShortMessage shortMessage, Date from, Date to, PagingBean pb) {
		return messageDao.searchShortMessage(userId, shortMessage, from, to, pb);
	}

	public ShortMessage save(Long senderId, String receiveIds, String content, Short msgType)
	  {
	    ShortMessage shortMessage = new ShortMessage();
	    shortMessage.setContent(content);
	    shortMessage.setMsgType(msgType);
	    AppUser curUser = (AppUser)this.appUserDao.get(senderId);
	    shortMessage.setSender(curUser.getFullname());
	    shortMessage.setSenderId(curUser.getUserId());
	    shortMessage.setSendTime(new Date());

	    this.messageDao.save(shortMessage);

	    String[] reIds = receiveIds.split("[,]");
	    if (reIds != null)
	    {
	      for (String userId : reIds) {
	        InMessage inMsg = new InMessage();
	        inMsg.setDelFlag(Constants.FLAG_UNDELETED);
	        inMsg.setReadFlag(InMessage.FLAG_UNREAD);
	        inMsg.setShortMessage(shortMessage);
	        AppUser receiveUser = (AppUser)this.appUserDao.get(new Long(userId));

	        inMsg.setUserId(receiveUser.getUserId());
	        inMsg.setUserFullname(receiveUser.getFullname());
	        this.inMessageDao.save(inMsg);
	      }
	    }

	    return shortMessage;
	  }

}
